package ink.xiaobaibai.advice;

import ink.xiaobaibai.response.ResponseFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-06-03
 **/

@RestControllerAdvice
@Slf4j
public class GlobalAdvice {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseFormat myMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("error:{}", e.getMessage());
        return ResponseFormat.failure(e.getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage());//返回第一个
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    public ResponseFormat myMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("error:{}", e.getMessage());
        return ResponseFormat.failure("请求参数错误");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseFormat requestMethodError() {
        return ResponseFormat.fail("请求方法错误");
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ResponseFormat requestBodyTypeError() {
        return ResponseFormat.fail("请求体格式错误");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseFormat notReadableException() {
        return ResponseFormat.fail("post请求未携带正确的body请求体");
    }

    @ExceptionHandler(ClientAbortException.class)
    public void notClientAbortException() {

    }

    @ExceptionHandler(IOException.class)
    public void ioException() {

    }

    @ExceptionHandler(Exception.class)
    public ResponseFormat exception(Exception e) {
        log.error("error:", e);
        return ResponseFormat.failure("服务器繁忙");
    }

}
